package com.tianhao.luo.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @author tianhao.luo@hand-china.com
 */
public class ForkJoinDemo {

    public static void main(String[] args) {
        // 创建拆分对象
        MyTask myTask = new MyTask(0, 100);
        try {
            // 创建分支合并池对象
            ForkJoinPool forkJoinPool = new ForkJoinPool();
            ForkJoinTask<Integer> submit = forkJoinPool.submit(myTask);
            Integer integer = submit.get();
            System.out.println(integer);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }


    static class MyTask extends RecursiveTask<Integer> {
        // 拆分差值不能超过10，计算10以内的运算
        public static final Integer VALUE = 10;
        // 拆分开始值
        private int begin;
        // 拆分结束值
        private int end;
        // 返回结果
        private int result;

        public MyTask(int begin, int end) {
            this.begin = begin;
            this.end = end;
        }

        // 拆分和合并的操作
        @Override
        protected Integer compute() {
            // 判断相加的两个数值是否大于10
            if ((end-begin)<=VALUE){
                // 相加操作
                for (int i = begin; i <= end; i++) {
                    result = result+i;
                }
            }else {
                // 进一步拆分
                int mid = (begin+end)/2;
                // 拆分
                MyTask myTask1 = new MyTask(begin, mid);
                MyTask myTask2 = new MyTask(mid+1, end);
                myTask1.fork();
                myTask2.fork();
                // 合并结果
                result = myTask1.join()+myTask2.join();
            }
            return result;
        }
    }
}
